<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use app\api\model\UUser;
use lan\Lan;
use think\Controller;

class  Base extends Controller {
    public $user_id;
    public $lanMsg; // 语言提示语
    public $lanType; // 语言类型   0 英文  1 西班牙   2 葡萄牙
    public $allowController = ['Apilogin', 'Base', 'Other']; // 不用拦截的控制器
    // 不用拦截的方法
    public $allowAction = [
        'Apilogin/sendcode',
        'Apilogin/emailregister',
        'Apilogin/login',
        'Apilogin/forgetpassword',
        'Other/getconfig',
        'Apilogin/emailregister',
        'Base/checkall',
        'Base/sendemail',
        'User/commitcheck',
        'User/userbaseinfo'
    ];

    // 构造函数
    public function __construct(){
        header("Access-Control-Allow-Origin:*");

        $this->lanMsg = new Lan();
        $this->lanType = input('lanType') ? input('lanType') : 0;
        $this->user_id = input('user_id') ? input('user_id') : 0;

        $controller = request()->controller();
        $model = request()->action();
        $fun = $controller . '/' . $model;
        if(!in_array($fun, $this->allowAction)){
            $loginStatus = $this->checkAll($this->user_id);
            if($loginStatus == 111){
                echo json_encode(['status' => 301, 'msg' => $this->lanMsg->userIdErr[$this->lanType]]);
                exit;
            }elseif ($loginStatus == 222){
                echo json_encode(['status' => 302, 'msg' => $this->lanMsg->prohibitLogin[$this->lanType]]);
                exit;
            }elseif ($loginStatus == 333){
                echo json_encode(['status' => 303, 'msg' => $this->lanMsg->userStatusErr[$this->lanType]]);
                exit;
            }
        }

    }

    /**
     * 统一验证
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid){
        if($uid == 0){
            return 111;
        }else{
            $user = UUser::findData(['user_id' => $uid]);
            if($user['user_type'] == 0){
                return 222;
            }else{
                if($user['user_status'] == 4 || $user['user_status'] == 5){
                    return 333;
                }
            }
        }
    }

    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
//        header("Content-type: text/html; charset=utf-8");
        $body_json = array(
            'sid'=>'05b0c3cc6133227764acc0e1b6ea21ad',
            'token'=>'42c56907ae16aa3615c3945e72e26249',
            'appid'=>'414eed7c02e146598852492fa626204d',
            'templateid'=>'400297',
            'param'=>$num,
            'mobile'=>$phone,
            'uid'=>'',
        );
        $body = json_encode($body_json);
        $header = array(
            'Accept:application/json',
            'Content-Type:application/json;charset=utf-8',
        );
        $url = 'https://open.ucpaas.com/ol/sms/sendsms';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($result,true);
        return $res;
    }

    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)
    public function uploadFile()
    {
        $tmp = $_FILES['image']['tmp_name'];
        $name = $_FILES['image']['name'];
        $size = $_FILES['image']['size'];
        if($size > 1024*1024*5){
            return json_encode(['status'=>0,'msg'=>"图片不得超过5M！"]);
        }
        $imgarray = array('jpg','jpeg','png');
        $dir = $_SERVER['DOCUMENT_ROOT'];
        $url =  "http://".$_SERVER['HTTP_HOST'];
        if($tmp){
            //=======重命名=====
            $rand = date('YmdHis').rand(100000,999999);
            $exe = explode('.',$name);
            $exe = end($exe);
//            if(!in_array($exe,$imgarray)){
//                return json_encode(['status'=>0,'msg'=>'图片格式不支持']);
//            }
//            $newName = $rand . '.' .$exe;
            $newName = $rand . '.png';
            //=======================
            if(move_uploaded_file($tmp,"{$dir}/image/{$newName}")){
                $imgUrl = "{$url}/image/{$newName}";
                if($size > 1024*1024*2){
                    $this->image_png_size_add("{$dir}/image/{$newName}","{$dir}/image/{$newName}");
                }
                return json_encode(['status'=>200,'msg'=>$imgUrl]);
            }else{
                return json_encode(['status'=>0,'msg'=>'图片保存失败']);
            }
        }else{
            return json_encode(['status'=>0,'msg'=>"上传一张图！"]);
        }
    }

    /**
     * 压缩图片
     * @param $imgsrc:原图片地址（完整的图片路径）
     * @param $imgdst:压缩后的图片地址，也是完整的
     */
    function image_png_size_add($imgsrc,$imgdst){
        list($width,$height,$type)=getimagesize($imgsrc);
        switch($type){
            case 1:
                break;
            case 2:
                header('Content-Type:image/jpeg');
                $image = imagecreatefromjpeg($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
            case 3:
                header('Content-Type:image/png');
                $image = imagecreatefrompng($imgsrc);
                imagejpeg($image, $imgdst,20);
                imagedestroy($image);
                break;
        }
    }

    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }

    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    /**
     * 发送邮件
     * @param $email    接收方邮箱
     * @param $code     验证码
     * @return array
     */
    public function sendEmail($email, $code){
        include_once(EXTEND_PATH . "phpmailer/class.phpmailer.php");
        include_once(EXTEND_PATH . "phpmailer/class.pop3.php");
        include_once(EXTEND_PATH . "phpmailer/class.smtp.php");
        include_once(EXTEND_PATH . "phpmailer/PHPMailerAutoload.php");
        try{
            $mail = new \PHPMailer();
            $mail -> isSMTP();                  //通过SMTP协议发送
            $mail -> CharSet = "utf-8";            //设置编码
//        $mail -> Port = 25;                   //设置端口

            // 由于阿里服务器禁用了25端口，所以将端口改成465，当需要加入ssl鉴权
            $mail->SMTPSecure = 'ssl';        //设置使用ssl加密方式登录鉴权
            $mail->Port = 465;                //设置ssl连接smtp服务器的远程服务器端口号


            //SMTP服务器是否需要验证(验证为true 不验证为false)
            $mail -> SMTPAuth = true;
            $mail -> Host = "smtp.126.com";           //设置主机服务器
            $mail -> Username = config('email.Username');   //发送者邮箱账号
//        $mail -> Password = "xianghui1688"; //发送者邮箱密码
            $mail -> Password = config('email.Password'); // 此密码需要使用成功开启IMAP/STMP时的授权码
            $mail -> From = config('email.Username'); //发送者是谁
            $mail -> FromName = "摩尔化工";       //发送者名称是谁
            $mail->AddAddress($email); //收件人邮箱
            $mail -> Subject = "摩尔化工"; //右键内容
            $mail -> Body = '【摩尔化工】你的验证码为：'. $code . '，有效期5分钟。如非本人操作，请忽略。';
            $mail -> ISHTML();//发送邮件是是否允许显示html代码
            $mail -> SMTPDebug = false;
            $mail -> Send();
            $return = ['code' => 200, 'msg' => true];
        }catch(\Exception $e){
            $return =  ['code' => 0, 'msg' => $mail->ErrorInfo];
        }
        return $return;
    }



}